<template>
    <el-container class="notification-container">
      <!-- 搜索框 -->
      <el-header class="search-header">
        <el-row :gutter="20" justify="space-between" align="middle" style="width: 100%;">
          <el-col :span="8">
            <el-input v-model="searchParams.username" placeholder="用户名" clearable style="padding: 10px !important;">
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-input v-model="searchParams.consultantName" placeholder="咨询师名称" clearable>
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" icon="Search" @click="handleSearch" style="padding: 20px;">搜索</el-button>
            <el-button plain icon="Refresh" @click="resetSearchForm" style="padding: 20px;">重置</el-button>
          </el-col>
        </el-row>
      </el-header>
  
      <!-- 通知表格 -->
      <el-main class="main-content">
        <el-table
          :data="notifications"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="consultantName" label="咨询师名称" width="180" />
          <el-table-column prop="consultationContent" label="咨询内容" width="200" />
          <el-table-column prop="notificationContent" label="通知内容" width="200" />
          <el-table-column prop="notificationTime" label="通知时间" width="180">
            <template #default="{ row }">
              <span>{{ formatDate(row.notificationTime) }}</span>
            </template>
          </el-table-column>
  
          <el-table-column label="操作" fixed="right" width="240">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
  
      <!-- 弹窗组件 -->
      <el-dialog
        v-model="dialogVisible"
        :title="currentDialogType === 'add' ? '添加通知' : currentDialogType === 'edit' ? '编辑通知' : '通知详情'"
        :width="currentDialogType === 'detail' ? '80%' : '600px'"
        class="notification-dialog"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" :disabled="currentDialogType === 'detail' || currentDialogType === 'edit'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="咨询师名称" prop="consultantName">
                <el-input v-model="form.consultantName" :disabled="currentDialogType === 'detail' || currentDialogType === 'edit'" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="咨询内容" prop="consultationContent">
                <el-input
                  v-model="form.consultationContent"
                  type="textarea"
                  :rows="3"
                  :disabled="currentDialogType === 'detail' "
                />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="通知内容" prop="notificationContent">
                <el-input
                  v-model="form.notificationContent"
                  type="textarea"
                  :rows="3"
                  :disabled="currentDialogType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="通知时间" prop="notificationTime">
                <el-date-picker
                  v-model="form.notificationTime"
                  type="datetime"
                  placeholder="选择通知时间"
                  :disabled="currentDialogType === 'detail' || currentDialogType === 'edit'"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <span v-if="currentDialogType !== 'detail'">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAction" :loading="submitLoading">
              确定
            </el-button>
          </span>
          <span v-else>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-container>
  </template>
  
  <script>
import { mapState, mapGetters, mapActions } from 'vuex';

export default {
  data() {
    return {
      dialogVisible: false,
      currentDialogType: 'add',
      submitLoading: false,
      form: {
        id: null,
        username: '',
        consultantName: '',
        consultationContent: '',
        notificationContent: '',
        notificationTime: null
      }
    }
  },
  computed: {
    ...mapState('notification', ['currentPage', 'pageSize', 'searchParams','notifications','total']),
    ...mapGetters('notification', [
      'currentNotifications',
      'pagination',
      'searchConditions',
      'isLoading'
    ])
  },
  mounted() {
    this.fetchNotificationsC();
  },
  methods: {
    ...mapActions('notification', [
      'fetchNotificationsC',
      'updateSearchParams',
      'handlePageChange',
      'deleteNotification',
      'updateNotification'
    ]),

    // 搜索处理
    handleSearch() {
      this.updateSearchParams({
        username: this.searchParams.username,
        consultantName: this.searchParams.consultantName
      });
    },

    //删除处理
    handleDelete(row){
        console.log('consultation',row);
        
        this.deleteNotification(row.id)

    },

    // 重置搜索
    resetSearchForm() {
      this.updateSearchParams({ username: '', consultantName: '' });
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.handlePageChange({ page: this.currentPage, size });
    },

    // 页码变化
    handleCurrentChange(page) {
      this.handlePageChange({ page, size: this.pageSize });
    },

    // 新增通知
    handleAdd() {
      this.currentDialogType = 'add';
      this.resetForm();
      this.dialogVisible = true;
    },

    // 编辑通知
    handleEdit(row) {
      this.currentDialogType = 'edit';
      this.form = { ...row };
      this.dialogVisible = true;
    },

    // 查看详情
    handleDetail(row) {
      this.currentDialogType = 'detail';
      this.form = { ...row };
      this.dialogVisible = true;
    },

    // 表单提交
    async handleConfirmAction() {
      try {
        await this.$refs.formRef.validate();
        this.submitLoading = true;
        
        // 这里调用实际API接口
        if (this.currentDialogType === 'add') {
          // await addNotification(this.form);
          this.$message.success('添加成功');
        } else {
          // await updateNotification(this.form);
          console.log('form', this.form);
          this.updateNotification(this.form);
        }
        
        this.dialogVisible = false;
        this.fetchNotificationsC();
      } catch (error) {
        console.error('操作失败:', error);
      } finally {
        this.submitLoading = false;
      }
    },

    // 删除确认
    handleDeleteConfirm() {
      this.$confirm('确定删除这条通知吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // await deleteNotification(row.id);
          this.fetchNotificationsC();
          this.$message.success('删除成功');
        } catch (error) {
          console.error('删除失败:', error);
        }
      });
    },

    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        username: '',
        consultantName: '',
        consultationContent: '',
        notificationContent: '',
        notificationTime: null
      };
      this.$refs.formRef?.resetFields();
    },

    // 日期格式化
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${
        d.getDate().toString().padStart(2,'0')} ${
        d.getHours().toString().padStart(2,'0')}:${
        d.getMinutes().toString().padStart(2,'0')}`;
    }
  }
}
</script>
  
  <style scoped>
  ::v-deep(.el-input__wrapper){
    padding: 5px !important;
  }


  .notification-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
  }
  
  .search-header {
    margin-bottom: 20px;
    padding: 40px;
    padding-top: 60px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    display: flex !important;
    justify-content: space-between !important;
    align-items: center !important;
    width: 100%;
  }
  
  .main-content {
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
  
  .notification-dialog {
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
  
  .dialog-form {
    padding: 24px;
  }
  
  .el-row {
    margin-bottom: 20px;
  }
  
  .el-col:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 768px) {
    .el-col {
      width: 100% !important;
    }
  }
  </style>